<template>
  <div v-loading="loading" element-loading-text="拼命加载中">
    <el-row>
       <!-- 搜索框 -->
        <el-col :span="24">
          <div class="search-wrapper">
            <ul class="search-box">
              <li><span class="filter-name">登录名：</span>
                <el-input style="width:150px" v-model="listQuery.loginName"></el-input></li>
              <li><span class="filter-name">用户名：</span>
                <el-input style="width:150px" v-model="listQuery.userName"></el-input></li>
              <li style="padding-left:10px;"><el-button style="vertical-align:middle;margin-top:-2px;" round size="mini" type="primary" @click="getList">查询</el-button></li>
            </ul>
          </div>
        </el-col>
      <!-- 按钮区 -->
      <el-col :span="24">
        <div class="button-wrapper">
          <el-button size="mini" type="primary" round @click="dialogFormVisible=true">增加</el-button>
          <el-button size="mini" type="warning" round  @click="batchEdit(9)">停用</el-button>
          <el-button size="mini" type="success" round  @click="batchEdit(0)">启动</el-button>
          <el-button size="mini" type="danger" round  @click="batchEdit(-1)">删除</el-button>
          <el-button size="mini" type="info" round  @click="restPass()">重置密码</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-col :span="24">
        <div class="data-wrapper">
          <template v-if="tableData!=null">
          <el-table ref="multipleTable" :data="tableData"  tooltip-effect="dark" style="width: 100%"
             @selection-change="handleSelectionChange">
            <el-table-column type="selection" label="全选" width="40">
            </el-table-column>
             <el-table-column type="index" label="序号" :index="indexMethod">
            </el-table-column>
            <el-table-column prop="userName" label="用户名称">
            </el-table-column>
            <el-table-column prop="userLoginname" label="登录名">
            </el-table-column>
            <el-table-column prop="regId.name" :show-overflow-tooltip="true" label="所属区域" >
            </el-table-column>
            <el-table-column prop="userPhone" label="用户电话" width="110">
            </el-table-column>
            <el-table-column prop="userEmail" :show-overflow-tooltip="true" label="用户邮箱" >
            </el-table-column>
            <el-table-column prop="userNote" :show-overflow-tooltip="true" label="备注">
            </el-table-column>
             <el-table-column prop="userState" label="状态" :formatter="formatState">
            </el-table-column>
            <el-table-column prop="updateTime" :show-overflow-tooltip="true" label="更新时间">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button title="角色绑定" size="small" icon="iconfont icon-role" type="primary" circle @click="handleBind(scope.$index, scope.row)"></el-button>
              <el-button title="编辑" size="small" icon="el-icon-edit" type="success" circle @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button title="删除" size="small" icon="el-icon-delete" type="danger" circle @click="handleDel(scope.$index, scope.row)"></el-button>
            </template>
           </el-table-column> 
          </el-table>
          </template>
        </div>
      </el-col>
    </el-row>
    <!-- 底部按钮和分页 -->
    <el-row :gutter="20" v-if="dataCount" type="flex" justify="space-between" align="center" class="page-wrapper">
      <el-col :span="20">
        <div class="page-item">
          <el-pagination background  
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page.sync="listQuery.currentPage" 
          :page-sizes="pageSizes" 
          :page-size="listQuery.pageSize" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="dataCount"/>
        </div>
      </el-col>
    </el-row>
    <!-- 弹出窗口区域 -->
    <el-dialog title="用户添加" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form"> 
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
              <el-input v-model="form.userName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名" :label-width="formLabelWidth" prop="userLoginname">
              <el-input v-model="form.userLoginname" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属区域" :label-width="formLabelWidth" prop="selectedAddress">
              <el-cascader class="width-all" 
              :options="treeData" 
              :props="addProps"
              :change-on-select="true"
              v-model="form.selectedAddress"
              @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>      
          <el-col :span="12">
            <el-form-item label="电话号码" :label-width="formLabelWidth" prop="userPhone">
              <el-input v-model="form.userPhone" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="userEmail">
              <el-input v-model="form.userEmail" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="userNote">
               <el-input type="textarea" v-model="form.userNote" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleCancel('form')">取 消</el-button>
        <el-button size="medium" type="primary" @click="insert('form')">确 定</el-button>
      </div>
    </el-dialog>

     <!-- 弹出窗口区域 -->
    <el-dialog title="用户修改" :visible.sync="editdialogForm">
        <el-form :model="oneCol" v-if="oneCol" :rules="editRules" ref="oneCol">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
              <el-input v-model="oneCol.userName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名" :label-width="formLabelWidth" prop="userLoginname">
              <el-input v-model="oneCol.userLoginname" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属区域" :label-width="formLabelWidth" prop="selectedAddress">
              <el-cascader :options="treeData" 
              :props="addProps" 
              :change-on-select="true"
              class="width-all"
              v-model="oneCol.selectedAddress" 
              @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>      
          <el-col :span="12">
            <el-form-item label="电话号码" :label-width="formLabelWidth" prop="userPhone">
              <el-input v-model="oneCol.userPhone" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="userEmail">
              <el-input v-model="oneCol.userEmail" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth">
               <el-input type="textarea" v-model="oneCol.userNote" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleCancel('oneCol')">取 消</el-button>
        <el-button size="medium" type="primary" @click="update('oneCol')">确 定</el-button>
      </div>
    </el-dialog>

    <!--角色绑定  -->
    <el-dialog title="角色绑定" :visible.sync="bindDialog">
      <el-table ref="multipleTable" :data="roleTableData"  tooltip-effect="dark" style="width: 100%"
              @selection-change="roleHandleSelectionChange">
              <el-table-column type="selection" label="全选" width="40">
              </el-table-column>
              <el-table-column type="index" label="序号" :index="roleIndexMethod">
              </el-table-column>
             <el-table-column prop="roleName" label="角色名称">
              </el-table-column>
              <el-table-column prop="roleType" label="角色类型" :formatter="formatType"> 
              </el-table-column>
            </el-table>
             <!-- 底部按钮和分页 -->
      <el-row :gutter="20" type="flex" justify="space-between" align="center" class="page-wrapper">
        <el-col :span="20">
          <div class="page-item">
            <el-pagination background  
            @size-change="roleHandleSizeChange" 
            @current-change="roleHandleCurrentChange"
            :current-page.sync="roleListQuery.currentPage" 
            :page-sizes="pageSizes" 
            :page-size="roleListQuery.pageSize" 
            layout="total, sizes, prev, pager, next, jumper" 
            :total="roleDataCount"/>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="bindDialog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="roleBind()">绑 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var editValidateLoginName = (rule, value, callback) => {
      if (!new RegExp("^[a-zA-Z]+$").test(value)) {
        callback(new Error("登录名只能使用英文字母组合"));
      } else {
        //验证用户名是否存在

        //发送登录名校验请求
        this.postRequest("/api/user/name/editcheck", {
          userLoginname: value,
          userId: this.oneCol.userId
        })
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              callback(new Error("登录名已存在!"));
            } else {
              callback();
            }
          })
          .catch(error => {
            //错误信息
            callback(new Error(error));
          });
      }
    };
    var validateLoginName = (rule, value, callback) => {
      if (!new RegExp("^[a-zA-Z]+$").test(value)) {
        callback(new Error("登录名只能使用英文字母组合"));
      } else {
        //验证用户名是否存在

        //发送登录名校验请求
        this.postRequest("/api/user/name/addcheck", { userLoginname: value })
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              callback(new Error("登录名已存在!"));
            } else {
              callback();
            }
          })
          .catch(error => {
            //错误信息
            callback(new Error(error));
          });
      }
    };
    return {
      editRules: {
        selectedAddress:[ { required: true, message: "请选择区域", trigger: "change" }],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        userLoginname: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { validator: editValidateLoginName, trigger: "blur" }
        ],
        userPhone: [
          {
            required: true,
            pattern: /^1[34578]\d{9}$/, //可以写正则表达式呦呦呦
            message: "目前只支持中国大陆的手机号码",
            trigger: "blur"
          }
        ],
        userEmail: [
          {
            required: true,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur"
          }
        ]
      },
      rules: {
         selectedAddress:[ { required: true, message: "请选择区域", trigger: "change" }],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        userLoginname: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { validator: validateLoginName, trigger: "blur" }
        ],
        userPhone: [
          {
            required: true,
            pattern: /^1[34578]\d{9}$/, //可以写正则表达式呦呦呦
            message: "目前只支持中国大陆的手机号码",
            trigger: "blur"
          }
        ],
        userEmail: [
          {
            required: true,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur"
          }
        ]
      },
      //用户数据
      tableData: [],
      //角色数据
      roleTableData: [],
      //默认数据总数
      dataCount: 100,
      //角色列表默认数据总数
      roleDataCount: 10,
      pageSizes: [5, 10, 20, 30, 40],
      //查询条件
      listQuery: {
        currentPage: 1,
        pageSize: 5
      },
      //角色列表条件
      roleListQuery: {
        currentPage: 1,
        pageSize: 5
      },
      listSelect: [],
      roleListSelect: [],
      dialogFormVisible: false,
      bindDialog: false,
      editdialogForm: false,
      loading: false,
      bindUserId: "",
      form: {},
      oneCol: {},
      formLabelWidth: "100px",
      addProps: {
          label:'regName',
          value:'regId',
          children: 'children'
        },
    };
  },
  mounted() {
    this.getList();
    this.getRoleList();
  },
  computed:{
    treeData:function(){
      return this.$store.state.dropTree
    }
  },
  methods: {
    //角色类型翻译
    formatType: function(row, column) {
      if (row.roleType == 0) {
        return "普通角色";
      } else if (row.roleType == 1) {
        return "管理员";
      } else if (row.roleType == 2) {
        return "超级管理员";
      }
    },
    // 状态翻译
    formatState: function(row, column) {
      return row.userState == 0 ? "启用" : "停用";
    },
    //用户列表查询
    getList() {
      this.loading = true;
      this.getRequest("/api/users", this.listQuery)
        .then(res => {
          var data = res.data;
          if (data.status == 200) {
            this.tableData = data.data;
            this.dataCount = data.count;
          } else {
            this.$message.error(data.msg);
          }
          this.loading = false;
        })
        .catch(error => {
          //错误信息
          this.$message.error(error);
        });
    },
    //角色列表查询
    getRoleList() {
      this.getRequest("/api/roles", this.listQuery)
        .then(res => {
          var data = res.data;
          if (data.status == 200) {
            this.roleTableData = data.data;
            this.roleDataCount = data.count;
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(error => {
          //错误信息
          this.$message.error(error);
        });
    },

    //搜索功能
    handSearch(val) {
      this.getList();
    },
    //新增
    insert(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.postRequest("/api/user", this.form)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.dialogFormVisible = false;
                this.getList();
                this.form = {};
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        } else {
          this.$message.error("error submit!!");
          return false;
        }
      });
    },
    //单个删除
    handleDel(index, row) {
      this.$confirm("确认删除？").then(_ => {
        this.deleteRequest("/api/user", { userId: row.userId })
          .then(res => {
            var data = res.data;
            this.$message.success(data.msg);
            this.getList();
          })
          .catch(error => {
            //错误信息
            this.$message.error(error);
          });
      });
    },
    //更新
    update(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.putRequest("/api/user", this.oneCol)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.editdialogForm = false;
                this.getList();
                this.oneCol = {};
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        } else {
          this.$message.error("error submit!!");
          return false;
        }
      });
    },
    //批量编辑
    batchEdit(val) {
      if (this.listSelect.length <= 0) {
        this.$message.warning("请选择一条数据");
        return;
      }

      var strArr = [];
      for (var i = 0; i < this.listSelect.length; i++) {
        strArr.push(this.listSelect[i].userId);
      }

      //前面三个参数分别是 表名，状态字段名，id字段名
      //status 为状态值 （0：正常  9：停用 -1：删除）
      //ids 为需要批量操作的 id数组
      var submitData = {
        tableName: "sys_user",
        tableCol: "user_state",
        tableId: "user_id",
        status: val,
        ids: strArr
      };

      this.$confirm("确认批量操作？")
        .then(_ => {
          this.putRequest("/api/common/batch", submitData)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.getList();
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    //重置密码
    restPass() {
      if (this.listSelect.length <= 0) {
        this.$message.warning("请选择一条数据");
        return;
      }

      var strArr = [];
      for (var i = 0; i < this.listSelect.length; i++) {
        strArr.push(this.listSelect[i].userId);
      }

      var submitData = {
        userIds: strArr
      };

      this.$confirm("确认重置密码？")
        .then(_ => {
          this.putRequest("/api/user/passwords", submitData)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.getList();
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    //用户列表复选框选中调用
    handleSelectionChange(val) {
      this.listSelect = val;
    },
    //角色列表复选框选中调用
    roleHandleSelectionChange(val) {
      this.roleListSelect = val;
    },
    //用户列表序号生成规则
    indexMethod(index) {
      return (
        index + 1 + (this.listQuery.currentPage - 1) * this.listQuery.pageSize
      );
    },
    //角色列表序号生成规则
    roleIndexMethod(index) {
      return (
        index +
        1 +
        (this.roleListQuery.currentPage - 1) * this.roleListQuery.pageSize
      );
    },
    //角色每页个数改变
    roleHandleSizeChange(size) {
      this.roleListQuery.pageSize = size;
      this.roleListQuery.currentPage = 1;
      this.getList();
    },
    //角色当前页改变
    roleHandleCurrentChange(currentPage) {
      this.roleListQuery.currentPage = currentPage;
      this.getList();
    },
    //用户每页个数改变
    handleSizeChange(size) {
      this.listQuery.pageSize = size;
      this.listQuery.currentPage = 1;
      this.getList();
    },
    //用户当前页改变
    handleCurrentChange(currentPage) {
      this.listQuery.currentPage = currentPage;
      this.getList();
    },
    //角色绑定弹窗
    handleBind(index, row) {
      this.bindUserId = row.userId;
      this.bindDialog = true;
    },
    //角色绑定
    roleBind() {
      if (this.roleListSelect.length <= 0) {
        this.$message.warning("请选择一个角色");
        return;
      }

      var strArr = [];
      for (var i = 0; i < this.roleListSelect.length; i++) {
        strArr.push(this.roleListSelect[i].roleId);
      }

      var submitData = {
        userId: this.bindUserId,
        roleIds: strArr
      };

      this.$confirm("确认绑定？")
        .then(_ => {
          this.postRequest("/api/user/rolebinding", submitData)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.getList();
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    //显示编辑弹窗
    handleEdit(index, row) {
      let rowData = Object.assign({}, row)
      this.oneCol = rowData;
      this.oneCol.regId = rowData.regId.code;

      var regId =  this.oneCol.regId;

      //区域下拉列表数据初始化
      var prefix = regId.substr(0,1);

      var codeValue = regId.substr(1);

      var count = codeValue.length/2;
      var subLen = 2;
      var codeArr=[];
      for(var i=0;i<count;i++){
        codeArr.push(prefix+codeValue.substr(0,subLen));
         subLen = subLen+2;
      }
       this.oneCol.selectedAddress = codeArr;
     
      this.editdialogForm = true;
    },
    // 树弹窗取消
    handleCancel(formName) {
      this.dialogFormVisible = false;
      this.editdialogForm = false;
      this.$refs[formName].resetFields();
    },
    //级联下拉框change事件
    handleChange(value) {
      this.oneCol.selectedAddress=value
      this.form.regId=value[value.length-1];
      this.oneCol.regId=value[value.length-1];
    }
  }
};
</script>
<style scoped>
</style>
